<?php
class Node_Model extends MY_Model {
	var $_table = "nodes";
	
	var $_table_meta = "nodes_meta";
	var $_field_meta_rel = "node_id";
	
	var $_table_hit = "nodes_hits";
	var $_field_hit_rel = "node_id";
	
	var $_hitsDateFormat = array(
		"day"	=> "%Y-%m-%d",
		"week"	=> "%Y-%W",
		"month"	=> "%Y-%m",
		"year"	=> "%Y"
	);
	
	var $_hits_name;
	
	function Node_Model() {
		parent::Model ();		
		
		$this->_hits_name = array(
			"total"		=> "total",
			"year" 		=> "year_" . mdate($this->_hitsDateFormat['year']),
			"month" 	=> "month_" . mdate($this->_hitsDateFormat['month']),
			"week" 		=> "week_" . mdate($this->_hitsDateFormat['week']),
			"day" 		=> "day_" . mdate($this->_hitsDateFormat['day'])		
		);
	}
	
	
	
	function getCategories($idNode, $category_parent = NULL){
		$this->db->select ( "*" );
		$this->db->from ( "categories" );
		$this->db->join ( "nodes_categories as nc", "nc.id_category = categories.id" );
		$this->db->where ( "nc.id_node", $idNode );
		
		if($category_parent != NULL){
			if(is_numeric($category_parent)){
				$this->db->like ( "categories.parents", "_{$category_pare}_" );
			} else{
				$this->db->like ( "categories.parents_name", "__{$category_parent}__" );
			}
		}

		$query = $this->db->get ();
		
		return $query->result ();
	}
	
	function getTags($idNode){
		$this->db->select ( "*" );
		$this->db->from ( "tags" );
		$this->db->join ( "nodes_tags as nc", "nc.tag_id = tags.id" );
		$this->db->where ( "nc.node_id", $idNode );

		$query = $this->db->get ();
		
		return $query->result ();
	}
	
	/**
	 * Crea un nodo.
	 * 
	 * array(
		"url_name"		=> string, 
		"language"		=> string, 
		"status"		=> string [draft, publish], 
		"user_created"	=> id, 
		"user_modified"	=> id, 
		"type"			=> string, 
		"title"			=> string, 
		
		"publish"		=> timestamp
		"expiration"	=> timestamp
		
		"data"			=> object | serialize string,
		
		"metas"	=> array(),
		"categories"	=> array(),
		"nodes"			=> array()
		
	 * )
	 */
	function create($node_data = array()){
			
		$defaults = array(
			"url_name" => "tmp", "language" => "ln", "status" => "draft",
			"user_created" => -1, "user_modified" => -1, 'created' => mdate($this->_dateFormat), 'modified' => mdate($this->_dateFormat), 
			"type" => "tmp", "title" => "tmp",
			"publish" => NULL, "expiration" => NULL, "data" => NULL,
			"metas" => array()
		);
		
		$node_data = array_merge($defaults, $node_data);
		
		$node_data["url_name"] = $this->getValidUrlName($node_data["url_name"]);
		
		if($node_data['publish'] != NULL){
			$node_data['publish'] = mdate($this->_dateFormat, $node_data['publish']);
		}
		
		if($node_data['expiration'] != NULL){
			$node_data['expiration'] = mdate($this->_dateFormat, $node_data['expiration']);
		}
		
		if($node_data['data'] != NULL && is_object($node_data['data'])){
			$node_data['data'] = serialize($node_data['data']);
		}
		
		$data = array(
			"url_name"		=> $node_data['url_name'], 
			"language"		=> $node_data['language'], 
			"status"		=> $node_data['status'], 
			"user_created"	=> $node_data['user_created'], 
			"user_modified"	=> $node_data['user_modified'],
			"created"		=> $node_data['created'], 
			"modified"		=> $node_data['modified'], 
			"type"			=> $node_data['type'], 
			"title"			=> $node_data['title'], 
			
			"publish"		=> $node_data['publish'],
			"expiration"	=> $node_data['expiration'],
			
			"data"			=> $node_data['data']
		);
			
		//TODO el idioma, tratarlo en las propiedades o en el contenido?

		$this->db->insert($this->_table, $data);
		
		$id = $this->db->insert_id();
		
		if($node_data['metas'] != NULL){
			foreach($node_data['metas'] as $key=>$value){
				$this->addMeta($id, $key, $value);
			}
		}
		
		return $id;		
	}
	/**
	 * Actualiza un nodo.
	 * 
	 * array(
 	  	"id"  			=> id, 
		"url_name"		=> string, 
		"language"		=> string, 
		"status"		=> string [draft, publish], 
		"user_created"	=> id, 
		"user_modified"	=> id, 
		"type"			=> string, 
		"title"			=> string, 
		
		"publish"		=> timestamp
		"expiration"	=> timestamp
		
		"data"			=> object | serialize string,
		
		"metas"			=> array(),
		"categories"	=> array(),
		"nodes"			=> array()
		
	 * )
	 * 
	 */
	function update($node_data = array()){
		$defaults = array(
			"id" => -1, "url_name" => "tmp", "language" => "ln", "status" => "draft",
			"user_created" => -1, "user_modified" => -1, 'modified' => mdate($this->_dateFormat), 
			"type" => "tmp", "title" => "tmp",
			"title" => "tmp", "publish" => NULL, "expiration" => NULL, "data" => NULL,
			"metas" => array(), "categories" => array(), "nodes" => array()
		);
		
		$node_data = array_merge($defaults, $node_data);
		
		$node = $this->get(array("id" => $node_data['id'], "status" => "all"));
		
		if($node !== FALSE){
			
			if($node_data["url_name"] != $node->url_name){
				$node_data["url_name"] = $this->getValidUrlName($node_data["url_name"]);
			}
			
			if($node_data['data'] != NULL && is_object($node_data['data'])){
				$node_data['data'] = serialize($node_data['data']);
			}
			
			if($node_data['publish'] != NULL){
				$node_data['publish'] = mdate($this->_dateFormat, $node_data['publish']);
			}
			
			if($node_data['expiration'] != NULL){
				$node_data['expiration'] = mdate($this->_dateFormat, $node_data['expiration']);
			}
			
			$data = array(
				"url_name"		=> $node_data['url_name'], 
				"language"		=> $node_data['language'], 
				"status"		=> $node_data['status'], 
				"user_modified"	=> $node_data['user_modified'], 
				"modified"		=> $node_data['modified'], 
				"type"			=> $node_data['type'], 
				"title"			=> $node_data['title'], 
				
				"publish"		=> $node_data['publish'],
				"expiration"	=> $node_data['expiration'],
				
				"data"			=> $node_data['data']
			);
			
			//TODO el idioma, tratarlo en las propiedades o en el contenido?		
			$this->db->where('id', $node_data['id']);
			$this->db->update($this->_table, $data);	
		
			if($node_data['metas'] != NULL){
				foreach($node_data['metas'] as $key=>$value){
					$this->addMeta($node_data['id'], $key, $value);
				}
			}
			
			return $node_data['id'];
		}

		return FALSE;		
	}
	
	
	function addCategories($idNode, $categories = NULL){
		if($categories != NULL){
			foreach($categories as $category){
				$this->addCategory($idNode, $category);
			}
		}
	}
	
	function addCategory($idNode, $idCategory){
		//Vamos a comprobar que no estubieran previamente asociados
		$categories = $this->getCategories($idNode);
		
		if($categories != NULL){
			foreach($categories as $category){
				if($category->id == $idCategory){
					return;
				}
			}
		}
		$data = array (
			'id_node' => $idNode,
			'id_category' => $idCategory
		);

		$this->db->insert("nodes_categories", $data);
	}
	
	function deleteCategory($idNode, $idCategory){
		$this->db->delete("nodes_categories", array('id_node' => $idNode, 'id_category' => $idCategory));
	}
	
	function deleteCategories($idNode){
		$this->db->delete("nodes_categories", array('id_node' => $idNode));
	}
	
	function addTags($idNode, $tags = NULL){
		if($tags != NULL){
			foreach($tags as $tag){
				$this->addTag($idNode, $tag);
			}
		}
	}
	
	function addTag($idNode, $idTag){
		$data = array (
			'node_id' => $idNode,
			'tag_id' => $idTag
		);

		$this->db->insert("nodes_tags", $data);
	}
	
	function deleteTag($idNode, $idTag){
		$this->db->delete("nodes_tags", array('node_id' => $idNode, 'tag_id' => $idTag));
	}
	
	function deleteTags($idNode){
		$this->db->delete("nodes_tags", array('node_id' => $idNode));
	}
	
	function delete($id){
		$this->db->delete($this->_table, array('id' => $id));
		$this->db->delete($this->_table_meta, array($this->_field_meta_rel => $id));
		$this->db->delete("nodes_categories", array('id_node' => $id));
		$this->db->delete("nodes_tags", array('node_id' => $id));
		$this->db->delete("nodes_nodes", array('id_node' => $id));
		$this->db->delete("nodes_nodes", array('id_node_rel' => $id));
	}
	
	
	/***** Metodos HITS *****/
	
	function updateCounters($node_id){
		foreach($this->_hits_name as $name=>$counter){
			$this->upHit($node_id, $counter);
		}		
	}
	
	function addHit($element_id, $key, $value, $single = FALSE){
		$valid = TRUE;
		if($single){
			$meta_value = $this->getHit($element_id, $key, TRUE);
			
			if($meta_value != NULL){
				$valid = FALSE;
			}
		}
		
		if($valid){
			$data = array (
				$this->_field_meta_rel	=> $element_id,
				'hit_key'				=> $key,
				'hit_value' 			=> $value
			);
	
			$this->db->insert($this->_table_hit, $data);
			
			return $this->db->insert_id();
		}
		
		return FALSE;
	}
	
	function updateHit($element_id, $key, $value){
		$this->db->where($this->_field_hit_rel, $element_id);
		$this->db->where("hit_key", $key);
		
		$data = array(
			"hit_value" => $value
		);
		
		$this->db->update($this->_table_hit, $data);
	}
	
	//TODO Probar
	function getActualHits($element_id){
		$this->db->from($this->_table_hit);
		$this->db->where($this->_field_hit_rel, $element_id);
		
		$where_query = "(";
		$pos=0;
		foreach($this->_hits_name as $hit_name=>$hit_field){
			if($pos > 0){
				$where_query .= " OR ";
			}
			
			$where_query .= "hit_key='$hit_field'";
			
			$pos++;
		}
		$where_query .= ")";		
		$this->db->where($where_query);
		
		$query = $this->db->get ();
		
		//Resultados
		$hit = $query->result ();
			
		$process_hits = array();
		foreach($hit as $m){
			if(isset($process_hits[$m->hit_key])){
				if(!is_array($process_hits[$m->hit_key])){
					$meta_tmp = $process_hits[$m->hit_key];
					$process_hits[$m->hit_key] = array();
					array_push($process_hits[$m->hit_key], $meta_tmp);
				}
				
				array_push($process_hits[$m->hit_key], $m);
			} else{
				$process_hits[$m->hit_key] = $m;
			}
		}
		
		//Console::log("Hits: " . print_r($process_hits, TRUE));
		
		$return_hits = array();
		foreach($this->_hits_name as $hit_name=>$hit_field){
			$hit_val = 0;
			if(isset($process_hits[$hit_field])){
				$hit_field_tmp = $process_hits[$hit_field];
				$hit_val = $hit_field_tmp->hit_value;
			}
			
			$return_hits[$hit_name] = $hit_val;
			
		}
		
		//Console::log("ret Hits: " . print_r($return_hits, TRUE));
		
		$hit = $return_hits;
		
		return $hit;		
	}
	
	function getHit($element_id, $key = NULL, $single = FALSE){
		$this->db->from($this->_table_hit);
		$this->db->where($this->_field_hit_rel, $element_id);
		
		if($key != NULL){
			$this->db->where("hit_key", $key);
		}
		
		$query = $this->db->get ();
		
		
		
		if($single){
			$hit = $query->row();
		} else{		
			$hit = $query->result ();
			
			$process_hits = array();
			foreach($hit as $m){
				if(isset($process_hits[$m->hit_key])){
					if(!is_array($process_hits[$m->hit_key])){
						$meta_tmp = $process_hits[$m->hit_key];
						$process_hits[$m->hit_key] = array();
						array_push($process_hits[$m->hit_key], $meta_tmp);
					}
					
					array_push($process_hits[$m->hit_key], $m);
				} else{
					$process_hits[$m->hit_key] = $m;
				}
			}
			
			$hit = $process_hits;
		}
		
		return $hit;
	}
	
	function upHit($element_id, $key){
		$meta = $this->getHit($element_id, $key, TRUE);
		
		if($meta == NULL){
			$value = 1;
			
			return $this->addHit($element_id, $key, $value, TRUE);
		} else{
			$value = $meta->hit_value + 1;
			
			return $this->updateHit($element_id, $key, $value);
		}		
	}
	
	
	
	
	
	
	
	
	
	function get($params = array(), $start = 0, $offset = -1){
		$params = $this->_getParams($params);
		
		$DB = $this->_get($params);
		
		$DB->select ( $this->_table . ".*" );
		
		/*if($params["num_comments"]){
			$DB->select ( "COUNT(cm_num_comments.comment_id) AS num_comments" );
		}*/
		
		$start = $params['start'];
		$offset = $params['offset'];
		
		if($offset != -1 && $start == -1){
			$start = 0;
		}
				
		if ($start != -1 && $offset != - 1) {
			$DB->limit ( $offset, $start );
		}
		
		$query = $DB->get ();
		
		if((isset($params['id']) && $params['id'] != NULL && $params['id'] !=-1) ||
			(isset($params['url_name']) && $params['url_name'] != NULL)){
				
			if ($query->num_rows() > 0){
				$data_cache = $query->row();
			} else{
				$data_cache = NULL;
			}
			
		} else{
			$data_cache = $query->result ();
		}
		
		return $data_cache;
	}
	
	function getCount($params = array()){
		$params = $this->_getParams($params);
		//$params['num_comments'] = FALSE;
		
		$DB = $this->_get($params);

		$data_cache = $DB->count_all_results ();
		
		return $data_cache;
	}
	
	function _getParams($params = array()){
		$defaults = array(
			"id"					=> NULL,
			"status"				=> "publish",
			"url_name"				=> NULL,
			"type"					=> NULL,
		
			"categories"			=> array(), //puede ser string: 3,4,name
			"categories_childs"		=> FALSE,
		
			"categories_or"			=> array(), //puede ser string: 3,4,name
			"categories_or_childs"	=> FALSE,
			
			"user"					=> array(),
		
			"metas"					=> array(),
			"metas_or"				=> array(),
			"metas_like"			=> array(),
			"metas_like_or"			=> array(),
			
			"tags"					=> array(), //puede ser string: 3,4,name
			"nodes"					=> array(), 
		
			"properties"			=> array(), // key => value
			
			//"num_comments"			=> FALSE,
		
			//nodes.*, meta.*
			"order"					=> array(
				$this->_table . ".publish" => "desc"
			),
			
			"start"					=> -1,
			"offset"				=> -1
		
		);
		
		$params = array_merge($defaults, $params);
		
		if($params['type'] != NULL && is_string($params['type'])){
			$params['type'] = split(",", $params['type']);
		}
		
		if($params['user'] != NULL && is_string($params['user'])){
			$params['user'] = split(",", $params['user']);
		}
		
		if($params['categories'] != NULL && is_string($params['categories'])){
			$params['categories'] = split(",", $params['categories']);
		}
		if($params['categories_or'] != NULL && is_string($params['categories_or'])){
			$params['categories_or'] = split(",", $params['categories_or']);
		}
		
		if($params['tags'] != NULL && is_string($params['tags'])){
			$params['tags'] = split(",", $params['tags']);
		}
		
		return $params;
	}
	
	function _get($params = array()){
		
		$this->db->from ( $this->_table );
		
		//Tratamos el estado
		if($params['status'] != NULL){
			if(is_string($params['status']) && $params['status'] != "all"){
				if($params['status'] == "publish"){
					$this->db->where ( $this->_table . ".status", $params['status'] );
					$this->db->where ( "($this->_table.publish IS NULL OR $this->_table.publish <= '".mdate($this->_dateFormat)."')");
					$this->db->where ( "($this->_table.expiration IS NULL OR $this->_table.expiration >= '".mdate($this->_dateFormat)."')");
				} else if($params['status'] == "future"){
					$this->db->where ( $this->_table . ".status", "publish" );
					$this->db->where ( "($this->_table.publish > '".mdate($this->_dateFormat)."')");
					$this->db->where ( "($this->_table.expiration IS NULL OR $this->_table.expiration >= '".mdate($this->_dateFormat)."')");
				} else if($params['status'] == "expire"){
					$this->db->where ( $this->_table . ".status", "publish" );
					$this->db->where ( "($this->_table.expiration < '".mdate($this->_dateFormat)."')");
				} else{
					$this->db->where ( $this->_table . ".status", $params['status'] );
				}
			} else if(is_array($params['status'])){
				$where_query = "(";
				$num_params = count($params['status']);
				foreach($params['status'] as $pos=>$status){
					$where_query .= $this->_table . ".status = '$status'";
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
		}
		
		//Tratamos el paramatro id o url_name, o si no filtramos por los demas parametros
		if($params['id'] != NULL && $params['id'] != -1){
			$this->db->where ( $this->_table . ".id", $params['id'] );
		} else if($params['url_name'] != NULL && $params['url_name'] != ""){
			$this->db->where ( $this->_table . ".url_name", $params['url_name'] );
		} else{
			
			if($params['type'] != NULL && is_array($params['type']) && count($params['type'])>0){
				$where_query = "(";
				$num_params = count($params['type']);
				foreach($params['type'] as $pos=>$type){
					$where_query .= $this->_table . ".type = '$type'";
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['user'] != NULL && is_array($params['user']) && count($params['user'])>0){
				$where_query = "(";
				$num_params = count($params['user']);
				foreach($params['user'] as $pos=>$user){
					$where_query .= $this->_table . ".user_created = '$user'";
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['categories'] != NULL && is_array($params['categories']) && count($params['categories'])>0){
				foreach($params['categories'] as $pos=>$category){
					$this->db->join ( "nodes_categories as nc_$pos", "nc_$pos.id_node = " . $this->_table . ".id" );
					$this->db->join ( "categories as c_$pos", "c_$pos.id = " . "nc_$pos.id_category" );
					if(is_numeric($category)){
						if(isset($params['categories_childs']) && $params['categories_childs'] === TRUE){
							//$this->db->like ( "c_$pos.parents", "_{$category}_" );
							$where = "(c_$pos.parents LIKE '%_{$category}_%' OR c_$pos.id=$category)";
							$this->db->where($where);
						} else{						
							$this->db->where("c_$pos.id", $category);
						}
					} else{
						if(isset($params['categories_childs']) && $params['categories_childs'] === TRUE){
							//No tenemos control con nombres de los padres....
						} 
						
						$this->db->where ( "c_$pos.url_name", $category );
					}
				}
			}
			
			if($params['categories_or'] != NULL && is_array($params['categories_or']) && count($params['categories_or'])>0){
				$this->db->join ( "nodes_categories as nc_or", "nc_or.id_node = " . $this->_table . ".id" );
				$this->db->join ( "categories as c_or", "c_or.id = " . "nc_or.id_category" );
				
				$where_query = "(";
				$num_params = count($params['categories_or']);
				foreach($params['categories_or'] as $pos=>$category){
					if(is_numeric($category)){
						$where_query .= "c_or.id = $category";
					} else{
						$where_query .= "c_or.url_name = '$category'";
					}
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['tags'] != NULL && is_array($params['tags']) && count($params['tags'])>0){
				$this->db->join ( "nodes_tags as nt", "nt.node_id = " . $this->_table . ".id" );
				$this->db->join ( "tags as t", "t.id = " . "nt.tag_id" );
				
				$where_query = "(";
				$num_params = count($params['tags']);
				foreach($params['tags'] as $pos=>$tag){
					if(is_numeric($tag)){
						$where_query .= "nt.tag_id = $tag";
					} else{
						$where_query .= "t.name = $tag";
					}
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['metas'] != NULL && is_array($params['metas']) && count($params['metas'])>0){
				$pos=0;
				foreach($params['metas'] as $meta_key=>$meta_value){
					$this->db->join ( "nodes_meta as nm_$pos", "nm_$pos.node_id = " . $this->_table . ".id" );
					$this->db->where( "nm_$pos.meta_key", $meta_key);
					$this->db->where( "nm_$pos.meta_value", $meta_value);
					
					$pos++;
				}
			}
			
			if($params['metas_or'] != NULL && is_array($params['metas_or']) && !empty($params['metas_or'])){
				$this->db->join ( "nodes_meta as nm", "nm.node_id = " . $this->_table . ".id" );
				
				$where_query = "(";
				$num_params = count($params['metas_or']);
				foreach($params['metas_or'] as $meta_key=>$meta_value){
					$where_query .= "(nm.meta_key = '$meta_key' AND nm.meta_value = '$meta_value')";
					if($pos < ($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['metas_like'] != NULL && is_array($params['metas_like']) && count($params['metas_like'])>0){
				$pos=0;
				foreach($params['metas_like'] as $meta_key=>$meta_value){
					$this->db->join ( "nodes_meta as nm_like_$pos", "nm_like_$pos.node_id = " . $this->_table . ".id" );
					$this->db->where( "nm_like_$pos.meta_key", $meta_key);
					$this->db->like( "nm_like_$pos.meta_value", $meta_value);
					
					$pos++;
				}
			}
			
			if($params['metas_like_or'] != NULL && is_array($params['metas_like_or']) && !empty($params['metas_like_or'])){
				$this->db->join ( "nodes_meta as nm_like_or", "nm_like_or.node_id = " . $this->_table . ".id" );
				
				$where_query = "(";
				$num_params = count($params['metas_like_or']);
				foreach($params['metas_like_or'] as $meta_key=>$meta_value){
					$where_query .= "(nm_like_or.meta_key = '$meta_key' AND nm_like_or.meta_value LIKE '%$meta_value%')";
					if($pos < ($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['order'] != NULL){
				if(is_string($params['order']) && $params['order'] == "rand"){
					$this->db->order_by ( "id", "RANDOM");
				} else{
					foreach($params['order'] as $field => $direction){
						
						$order_info = $direction;
						
						$order_direction = "ASC";
						$order_type = "STRING";
						
						if(is_array($order_info)){
							if(isset($order_info['direction'])){
								$order_direction = $order_info['direction'];
							}
							
							if(isset($order_info['type'])){
								$order_type = $order_info['type'];
							}
							
						} else{
							$order_info = strtoupper($order_info);
							if(strpos($order_info, "ASC") !== FALSE){
								$order_direction = "ASC";
							}
							
							if(strpos($order_info, "DESC") !== FALSE){
								$order_direction = "DESC";
							}
							
							if(strpos($order_info, "STRING") !== FALSE){
								$order_type = "STRING";
							}
							
							if(strpos($order_info, "INTEGER") !== FALSE){
								$order_type = "INTEGER";
							}
							
						}
						
						//Ordenamos por un campo meta
						if(strpos($field, "meta.") === 0){
							$meta_key = substr($field, strlen(".meta"));
							$meta_key_name = str_replace("-", "_", $meta_key); 
							$meta_key_name = "nm_{$meta_key_name}_order";
							
							$this->db->join ( "nodes_meta as $meta_key_name", "($meta_key_name.node_id = {$this->_table}.id AND $meta_key_name.meta_key = '$meta_key')", "left" );
							if($order_type ==  "INTEGER"){
								$this->db->select("$meta_key_name.meta_value+0 AS $meta_key_name", FALSE);
								$this->db->order_by ( "$meta_key_name $order_direction" );
							} else{
								$this->db->order_by ( "$meta_key_name.meta_value $order_direction" );
							}
							
						} if(strpos($field, "hit.") === 0){
							$hit_key = substr($field, strlen("hit."));
							
							if(isset($this->_hits_name[$hit_key])){
								$hit_key = $this->_hits_name[$hit_key];
								
								$hit_key_name = str_replace("-", "_", $hit_key); 
								$hit_key_name = "nhit_{$hit_key_name}_order";
								
								$this->db->join ( "nodes_hits as $hit_key_name", "($hit_key_name.node_id = {$this->_table}.id AND $hit_key_name.hit_key = '$hit_key')", "left" );
								$this->db->select("$hit_key_name.hit_value AS $hit_key_name", FALSE);
								$this->db->order_by ( "$hit_key_name.hit_value $order_direction" );
							}
							
						} else{
							$this->db->order_by ( "$field $order_direction" );
						}
					}
				}
			}
			
			/*if($params["num_comments"]){
				$this->db->join("comments as cm_num_comments", "cm_num_comments.node_id = {$this->_table}.id", "left");
				$this->db->group_by("{$this->_table}.id");
			}*/
			
			
		}
		
		return $this->db;
	}
	
	
	
	/*
	function getByUrlName($urlName) {
		$this->db->select ( $this->_table . ".*" );
		$this->db->from ( $this->_table );
		//$this->db->join ( "types", "types.id = " . $this->_table . ".type_id" );
		$this->db->where ( $this->_table . ".url_name", $urlName );

		$query = $this->db->get ();
		
		if ($query->num_rows() > 0){
			return $query->row();
		}

		return FALSE;
	}
	
	function getById($id) {
		$this->db->select ( $this->_table . ".*" );
		$this->db->from ( $this->_table );
		//$this->db->join ( "types", "types.id = " . $this->_table . ".type_id" );
		$this->db->where ( $this->_table . ".id", $id );

		$query = $this->db->get ();
		
		if ($query->num_rows() > 0){
			return $query->row();
		}

		return FALSE;
	}
	*/
	
}
?>
